import axios, { HttpStatusCode } from 'axios'
import { ElMessage } from 'element-plus'
import router from '@/router'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 封装axios
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API, // 设置默认的请求地址
  timeout: 10000,
})
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.set('Authorization', token)
    }
    // 在发送
    return config
  },
  (error) => {
    // 对请求错误做些什么
  }
)
// 响应拦截
service.interceptors.response.use(
  (response) => {
    const { data, status, statusText } = response
    const { code, message } = data
    if (status !== HttpStatusCode.Ok) {
      return Promise.reject(new Error(statusText || 'Error'))
    }
    if (code === HttpStatusCode.NotFound) {
      ElMessage.warning(message)
      return Promise.reject(new Error('请求资源不存在'))
    }
    if (code === HttpStatusCode.Forbidden) {
      ElMessage.warning(message)
      return Promise.reject(new Error('未授权'))
    }
    if (code === HttpStatusCode.Unauthorized) {
      ElMessage.warning(message)
      localStorage.removeItem('token')
      router.replace('/login?redirect=' + router.currentRoute.value.path)
      return Promise.reject(new Error(message))
    }
    if (code === HttpStatusCode.BadRequest) {
      ElMessage.warning(message)
      return Promise.reject(new Error(message))
    }
    return response
    // 对响应数据做点什么
  },
  (err) => {
    const { error } = err.response.data
    ElMessage.error(err)
    return Promise.reject(error)
  }
)
export default service

export enum ContentTypeEnum {
  json = 'application/json;charset=UTF-8',
  form = 'application/x-www-form-urlencoded;charset=UTF-8',
  multipart = 'multipart/form-data;charset=UTF-8',
}
